const app = getApp()
var api = require('../../utils/api.js')
var util = require('../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      windowHeight: app.globalData.windowHeight
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.addressList();
  },
  //地址请求
  addressList: function () {
    var params = new Object()
    var that = this;
    api.POST({
      params: params,
      url: app.globalData.base_url + 'address/list',
      success: function (res) {
        if (util.isEmpty(res.data.code)) {
          that.setData({
            address: res.data.data.address_list
          })
        }
      },
      fail: function (fail) {
        util.showError("登录失败，请检查网络");

      }
    })
  },
  //修改地址
  editorAddress: function (e) {
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/addAddress/addAddress?aid=' + id
    })
  },
  //删除地址
  deleteAddress: function (e) {
    var id = e.currentTarget.dataset.id;
    var that = this;

    wx.showModal({
      title: '提示',
      content: '确认删除该地址?',
      confirmColor:"#e51927",
      success: function (res) {
        if (res.confirm) {
          api.POST({
            params: { aid: id },
            url: app.globalData.base_url + 'address/del',
            success: function (res) {
              if (util.isEmpty(res.data.code)) {
                util.showStatus("删除成功")
                that.addressList();
              }
            },
            fail: function (fail) {
              util.showError("登录失败，请检查网络");

            }
          })
        } else if (res.cancel) {
          // console.log('用户点击取消')
        }
      }
    })


    
  },
  //添加新地址
  addAddress: function () {
    wx.navigateTo({
      url: '../addAddress/addAddress'
    })
  },

  radioChange: function (e) {
    var id = e.detail.value
    var that = this;
    var list = that.data.address;
    for (var i = 0; i < list.length; i++) {
      if (list[i].aid == id) {
        var params = {
          aid: id,
          username: list[i].username,
          mobile: list[i].mobile,
          province: list[i].province.name,
          town: list[i].town.name,
          city: list[i].city.name,
          address: list[i].address,
          is_default: 1,
          street: list[i].street.name
        }
        api.POST({
          params: params,
          url: app.globalData.base_url + 'address/modify',
          success: function (res) {
            if (util.isEmpty(res.data.code)) {
              that.addressList();
            }
          },
          fail: function (fail) {
            util.showError("登录失败，请检查网络");

          }
        })

      }
    }
  },
})